var networkSourceJs = require("./networkSource.js");

//播放音标函数
var playMusic = function(itemView, url) {
    if (url == null || url == "") {
        toastLog("网址错误：" + url);
        return false;
    }
    if (itemView != null)
        ui.post(() => {
            itemView.attr("tint", "#29B6F6");
        });
    try {
        var res = http.get(url);
    } catch (e) {
        if (itemView != null)
            ui.post(() => {
                itemView.attr("tint", "#000000");
            });
        log(e);
        toast("播放错误！");
        return false;
    }
    files.writeBytes("./vedios.mp3", res.body.bytes());
    media.playMusic("./vedios.mp3");
    sleep(media.getMusicDuration());
    if (itemView != null)
        ui.post(() => {
            itemView.attr("tint", "#000000");
        });
    return true;
}

var playMusicFromWord = function(itemView, word, type) {
    if (word.search(/\w/)) {
        return false;
    }
    
    var url = networkSourceJs.getMp3(word, type);
    
    if (itemView != null)
        ui.post(() => {
            itemView.attr("tint", "#29B6F6");
        });
    try {
        var res = http.get(url);
    } catch (e) {
        if (itemView != null)
            ui.post(() => {
                itemView.attr("tint", "#000000");
            });
        log(e);
        toast("播放错误！");
        return false;
    }
    files.writeBytes("./vedios.mp3", res.body.bytes());
    media.playMusic("./vedios.mp3");
    sleep(media.getMusicDuration());
    if (itemView != null)
        ui.post(() => {
            itemView.attr("tint", "#000000");
        });
    return true;
}

module.exports = {
    playMusic: playMusic,
    playMusicFromWord: playMusicFromWord
}